<?php
namespace App\Http\Controllers\Admin;

use App\AmountQuoteLog;
use App\Member;
use App\Product_order;
use App\QuoteBillMonth;
use App\QuoteBillMonthFenqi;
use App\QuoteBillMonthOrder;
use App\QuoteBillOverdue;
use App\QuoteFenqiDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Realname;
use App\AmountQuoteExtrainfo;
use App\AmountQuote;
use App\Services\PayLog;
use App\Services\Youyuapi;

class QuoteManagerController extends AdminController
{

    /**
     * 额度申请--列表
     * 
     * @param Request $request
     */
    public function quoteEduList(Request $request)
    {
        $name = trim($request->input('name', ''));
        $phone = trim($request->input('phone', ''));
        $idcard = trim($request->input('idcard', ''));
        $edu = trim($request->input('edu', ''));
        $status = trim($request->input('status', ''));
        $page = trim($request->input('page', 0)); // 页码
        $pagenumber = trim($request->input('pagenumber', '30')); // 分页个数
        
        $sql = "select d.status, d.id, d.member_id, c.realname,a.phone,c.card_id, b.credit_amount,b.amount_used,b.amount_remain  from mega_amount_quote_extrainfo as d left join mega_member as a on a.id=d.member_id left join mega_amount_quote as b on d.member_id = b.member_id left join mega_realname as c on d.member_id = c.member_id  where 1";
        $sqlcount = "select count(d.id) as count from mega_amount_quote_extrainfo as d left join mega_member as a on a.id=d.member_id left join mega_amount_quote as b on d.member_id = b.member_id left join mega_realname as c on d.member_id = c.member_id  where 1 ";
        $param = array();
        $sqlwhere = '';
        if ($idcard) {
            $sqlwhere .= " and c.card_id=:card_id ";
            $param[':card_id'] = $idcard;
        }
        if ($name) {
            $name = "%$name%";
            $sqlwhere .= " and c.realname like :realname ";
            $param[':realname'] = $name;
        }
        if ($phone) {
            $sqlwhere .= " and a.phone=:phone ";
            $param[':phone'] = $phone;
        }
        if ($edu) {
            $sqlwhere .= " and b.credit_amount=:edu ";
            $param[':edu'] = $edu;
        }
        if ($status) {
            $sqlwhere .= " and d.status=:status ";
            $param[':status'] = $status;
        }
        $start = $page * $pagenumber;
        $limit = " limit $start, $pagenumber ";
        $results = DB::select($sql . $sqlwhere . $limit, $param);
        $count = DB::select($sqlcount . $sqlwhere, $param);
        
        $data = array(
            'count' => $count[0]->count,
            'items' => $results,
            'page' => $page
        );
        
        $this->output($data);
    }

    /**
     * 额度申请--审核界面信息
     * 
     * @param Request $request
     */
    public function quoteEduInfo(Request $request)
    {
        $member_id = $request->input('member_id');
        $extraInfo = AmountQuoteExtrainfo::where('member_id',$member_id)->first();
        $images = array();
        $typeArray = array(
            'banklist',
            'credit',
            'house',
            'car',
            'driver',
            'idcard',
            'shouru',
            'other',
            'hetong'
        );
        foreach ($typeArray as $colum) {
            if ($extraInfo->$colum) {
                $files = explode(",", $extraInfo->$colum);
                foreach ($files as $file){
                    $images[] = $this->base64Img(storage_path() . DIRECTORY_SEPARATOR . 'amountextra' . DIRECTORY_SEPARATOR . $file);
                }
            }
        }
        $Quote = AmountQuote::where('member_id', $extraInfo->member_id)->first(); 
        $this->output(array('images'=> $images, 'amount'=>$Quote->credit_amount));
    }
    
    /**
     * 修改用户额度
     */
    public function updateQuoteEdu(Request $request){
        $member_id = $request->input('member_id');
        $quotenewedu = $request->input('quotenewedu');
        $adminId = $request->input('adminid');
        
        $Quote = AmountQuote::where('member_id', $member_id)->first(); 
        $oldAmount = $Quote->credit_amount;
        $Quote->credit_amount = $quotenewedu;
        $Quote->amount_remain = $Quote->credit_amount - $Quote->amount_used;
        $Quote->save();
        $extraInfo = AmountQuoteExtrainfo::where('member_id',$member_id)->first();
        $extraInfo->status = 2;
        $extraInfo->admin = $adminId;
        $extraInfo->save();
        //日志
        $member = Member::where('id', $member_id)->first();
        $QuoteChangeLog = New AmountQuoteLog();
        $QuoteChangeLog->member_id = $member_id;
        $QuoteChangeLog->member_name = $member->name;
        $QuoteChangeLog->type = 2;
        $QuoteChangeLog->amount = $Quote->credit_amount-$oldAmount;
        $QuoteChangeLog->remark = '后台管理员'.$adminId.'调整额度从'.$oldAmount.'调整至'.$Quote->credit_amount;
        $QuoteChangeLog->add_time = time();
        $QuoteChangeLog->save();
        
        //去油鱼修改额度
        $youyu = new Youyuapi();
        $url = "Lamijia/reg/eduset";
        // 手机号，金额，借款期限，利率5
        $data = array(
            'phone' => $member->phone, 
            'newamount' => $Quote->credit_amount * 1.1, 
        );
        $log = new PayLog('youyu_edu_log');
        $log->log("修改额度参数：");
        $log->log(json_encode($data));
        $result = $youyu->query($url, $data);
        $log->log("修改额度参数：");
        $log->log(json_encode($result));
        $log->logclose();
        
        $this->output(array(), 'success');
    }

    /**
     * 读取图片文件base64编码
     */
    private function base64Img($file)
    {
        if(file_exists($file)){ // && exif_imagetype($file)
            if ($fp = fopen($file, "rb", 0)) {
                $gambar = fread($fp, filesize($file));
                fclose($fp);
                $base64 = chunk_split(base64_encode($gambar));
                return $base64;
            }
        }
        return '';
    }

    /**
     * 额度管理--列表
     * 
     * @param Request $request
     */
    public function memberlist(Request $request)
    {
        $name = trim($request->input('name', ''));
        $phone = trim($request->input('phone', ''));
        $idcard = trim($request->input('idcard', ''));
        $edu = trim($request->input('edu', ''));
        $page = trim($request->input('page', 0)); // 页码
        $pagenumber = trim($request->input('pagenumber', '30')); // 分页个数
        $sql = "select a.id, c.realname,a.phone,c.card_id, b.credit_amount,b.amount_used,b.amount_remain from mega_member as a left join mega_amount_quote as b on a.id=b.member_id left join mega_realname as c on a.id = c.member_id where 1 ";
        $sqlcount = "select count(a.id) as count from mega_member as a left join mega_amount_quote as b on a.id=b.member_id left join mega_realname as c on a.id = c.member_id where 1 ";
        $param = array();
        $sqlwhere = '';
        if ($idcard) {
            $sqlwhere .= " and c.card_id=:card_id ";
            $param[':card_id'] = $idcard;
        }
        if ($name) {
            $name = "%$name%";
            $sqlwhere .= " and c.realname like :realname ";
            $param[':realname'] = $name;
        }
        if ($phone) {
            $sqlwhere .= " and a.phone=:phone ";
            $param[':phone'] = $phone;
        }
        if ($edu) {
            $sqlwhere .= " and b.credit_amount=:edu ";
            $param[':edu'] = $edu;
        }
        $start = $page * $pagenumber;
        $limit = " limit $start, $pagenumber ";
        $results = DB::select($sql . $sqlwhere . $limit, $param);
        $count = DB::select($sqlcount . $sqlwhere, $param);
        
        $data = array(
            'count' => $count[0]->count,
            'items' => $results,
            'page' => $page
        );
        
        $this->output($data);
    }

    /**
     * 逾期列表
     * 
     * @param Request $request
     */
    public function overduelist(Request $request)
    {
        $name = trim($request->input('name', ''));
        $phone = trim($request->input('phone', ''));
        $idcard = trim($request->input('idcard', ''));
        $type = trim($request->input('type', '')); // 1 逾期中，2已还清
        $page = trim($request->input('page', 0)); // 页码
        $pagenumber = trim($request->input('pagenumber', '30')); // 分页个数
        
        $sql = "select a.member_id,c.realname,b.phone,c.card_id, a.bill_year, a.bill_month, a.amount, a.overdue_fee,a.status from mega_quote_bill_overdue as a left join mega_member as b on b.id=a.member_id left join mega_realname as c on a.member_id = c.member_id where 1";
        $sqlcount = "select count(a.member_id) as count from mega_quote_bill_overdue as a left join mega_member as b on b.id=a.member_id left join mega_realname as c on a.member_id = c.member_id where 1";
        $param = array();
        $sqlwhere = '';
        if ($idcard) {
            $sqlwhere .= " and c.card_id=:card_id ";
            $param[':card_id'] = $idcard;
        }
        if ($name) {
            $name = "%$name%";
            $sqlwhere .= " and c.realname like :realname ";
            $param[':realname'] = $name;
        }
        if ($phone) {
            $sqlwhere .= " and b.phone=:phone ";
            $param[':phone'] = $phone;
        }
        if ($type) {
            $sqlwhere .= " and a.status=:type ";
            $param[':type'] = $type;
        }
        $start = $page * $pagenumber;
        $limit = " limit $start, $pagenumber ";
        $results = DB::select($sql . $sqlwhere . $limit, $param);
        $count = DB::select($sqlcount . $sqlwhere, $param);
        $data = array(
            'count' => $count[0]->count,
            'items' => $results,
            'page' => $page
        );
        $this->output($data);
    }

    /**
     * 逾期明细
     * 
     * @param Request $request
     */
    public function overduedetail(Request $request)
    {
        $memberId = trim($request->input('member_id', ''));
        $currentMonth = date('m', strtotime(date('Y') . "-" . date('m') . "-10" . " - 1 month"));
        $currentYear = date('Y', strtotime(date('Y') . "-" . date('m') . "-10" . " - 1 month"));
        $quoteBillMonth = QuoteBillMonth::where('member_id', $memberId)->where('bill_year', $currentYear)
            ->where('bill_month', $currentMonth)
            ->first();
        // 旧的逾期账单
        if ($quoteBillMonth) {
            $Overdues = QuoteBillMonth::where('member_id', $memberId)->where('id', '<>', $quoteBillMonth->id)
                ->where('status', 3)
                ->get();
        } else {
            $Overdues = QuoteBillMonth::where('member_id', $memberId)->where('status', 3)->get();
        }
        $data = array();
        $data['current'] = array(
            'amount' => '0',
            'benjin' => '0',
            'fee' => '0'
        );
        if ($quoteBillMonth && $quoteBillMonth->status == 3) {
            $data['current'] = array(
                'amount' => $quoteBillMonth->pay_amount_total,
                'benjin' => $quoteBillMonth->amount_total,
                'fee' => $quoteBillMonth->delay_amount_total
            );
        }
        $data['history'] = array();
        foreach ($Overdues as $Overdue) {
            // var_dump($Overdue->id);exit;
            $overdueObj = QuoteBillOverdue::where('bill_id', $Overdue->id)->first();
            // var_dump($overdueObj);exit;
            $data['history'][] = array(
                'title' => "{$Overdue->bill_year}年{$Overdue->bill_month}月",
                'benjin' => $Overdue->amount_total,
                'date' => substr($Overdue->pay_date, 0, 10),
                'day_number' => $overdueObj->day_number,
                'lixi' => $overdueObj->interest,
                'faxi' => $overdueObj->interest_punish,
                'znj' => 0
            );
        }
        $this->output($data);
    }

    /**
     * 还款管理
     */
    public function payQuoteList(Request $request)
    {
        $name = trim($request->input('name', ''));
        $phone = trim($request->input('phone', ''));
        $idcard = trim($request->input('idcard', ''));
        $type = trim($request->input('type', '')); // 0全部，1 正常，2逾期中
        $page = trim($request->input('page', 0)); // 页码
        $pagenumber = trim($request->input('pagenumber', '30')); // 分页个数
        
        $sql = "select b.member_id, b.realname , a.phone, b.card_id from mega_member as a inner join mega_realname as b on a.id = b.member_id ";
        $sqlcount = "select count(a.id) as count  from mega_member as a inner join mega_realname as b on a.id = b.member_id ";
        $param = array();
        $sqlwhere = '';
        if ($idcard) {
            $sqlwhere .= " and b.card_id=:card_id ";
            $param[':card_id'] = $idcard;
        }
        if ($name) {
            $name = "%$name%";
            $sqlwhere .= " and b.realname like :realname ";
            $param[':realname'] = $name;
        }
        if ($phone) {
            $sqlwhere .= " and a.phone=:phone ";
            $param[':phone'] = $phone;
        }
        if ($type == 1) { // 正常没逾期的
            $sqlwhere .= " and a.id not in(select member_id from mega_quote_bill_overdue where status = 1) ";
        } elseif ($type == 2) { // 逾期中
            $sqlwhere .= " and a.id in(select member_id from mega_quote_bill_overdue where status = 1) ";
        }
        $start = $page * $pagenumber;
        $limit = " limit $start, $pagenumber ";
        // echo $sql. $sqlwhere. $limit;
        $results = DB::select($sql . $sqlwhere . $limit, $param);
        $count = DB::select($sqlcount . $sqlwhere, $param);
        $items = array();
        foreach ($results as $objItem) {
            $hasOverdue = QuoteBillOverdue::where('member_id', $objItem->member_id)->where('status', 1)->first();
            $overdue_count = QuoteBillOverdue::where('member_id', $objItem->member_id)->count();
            $repayment_count = QuoteBillMonth::where('member_id', $objItem->member_id)->where('status', 2)->count();
            $items[] = array(
                'member_id' => $objItem->member_id,
                'phone' => $objItem->phone,
                'realname' => $objItem->realname,
                'card_id' => $objItem->card_id,
                'repayment_count' => $repayment_count,
                'overdue_count' => $overdue_count,
                'status' => $hasOverdue ? '逾期中' : '正常'
            );
        }
        
        $data = array(
            'count' => $count[0]->count,
            'items' => $items,
            'page' => $page
        );
        $this->output($data);
    }

    /**
     * 还款记录-个人账单详情
     */
    public function repaydetail(Request $request)
    {
        $memberId = trim($request->input('member_id', ''));
        $realInfo = Realname::where('member_id', $memberId)->first();
        $member = Member::find($memberId);
        $quoteMonths = QuoteBillMonth::where('member_id', $memberId)->get();
        $data = array();
        $items = array();
        $data['name'] = $realInfo ? $realInfo->realname : '';
        $data['phone'] = $member ? $member->phone : '';
        $data['card_id'] = $realInfo ? $realInfo->card_id : '';
        foreach ($quoteMonths as $quoteMonth) {
            $status = '待还';
            $type = '';
            $paydate = '';
            if ($quoteMonth->status == 2) {
                $status = '已还清';
                if ($quoteMonth->need_fenqi == 1 || $quoteMonth->need_fenqi == 2) {
                    $type = '全额还款';
                }
                if ($quoteMonth->need_fenqi == 3) {
                    $type = '分期';
                }
                $paydate = substr($quoteMonth->updated_at, 0, 10);
            }
            if ($quoteMonth->status == 3) {
                $status = '逾期';
            }
            
            $items[] = array(
                'quotemonthid' => $quoteMonth->id,
                'date' => $quoteMonth->bill_year . '年' . $quoteMonth->bill_month . '月',
                'amount' => $quoteMonth->amount_total,
                'status' => $status,
                'type' => $type,
                'paydate' => $paydate
            );
        }
        $data['items'] = $items;
        $this->output($data);
    }

    /**
     * 账单详情
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function quoteMonthDetail(Request $request)
    {
        $quotemonthid = trim($request->input('quotemonthid', ''));
        $id = $quotemonthid;
        $quoteBillMonth = QuoteBillMonth::where('id', $id)->first();
        $m = (int) $quoteBillMonth->bill_month;
        $result = array(
            'title' => "{$quoteBillMonth->bill_year}年{$m}月账单明细"
        );
        // 分期信息
        $result['fenqi'] = array();
        $MonthFenqis = QuoteBillMonthFenqi::where('bill_id', $quoteBillMonth->id)->get();
        foreach ($MonthFenqis as $item) {
            $fenqiDetail = QuoteFenqiDetail::where('id', $item->fenqi_id)->first();
            $result['fenqi'][] = array(
                'title' => date('n', strtotime($fenqiDetail->created_at)) . '月份分期(第' . $fenqiDetail->number_current . '期/共' . $fenqiDetail->number_totla . '期)',
                'date' => date('Y年m月d日', strtotime($item->created_at)),
                'amount' => sprintf('%.2f', $item->amount)
            );
        }
        // 消费信息
        $result['xiaofei'] = array();
        $monthOrders = QuoteBillMonthOrder::where('bill_id', $quoteBillMonth->id)->get();
        foreach ($monthOrders as $item) {
            $order = Product_order::withTrashed()->where('id', $item->order_id)->first();
            
            $shopInfo = Member::find($order->member_id);
            $result['xiaofei'][] = array(
                'title' => '线上订单消费-' . $shopInfo->name,
                'fenqi_amount' => sprintf('%.2f', $order->product_price + $order->logistics_price),
                'quankuan_amount' => sprintf('%.2f', $order->product_price * 1.1 + $order->logistics_price * 1.1),
                'date' => date('Y年m月d日', $order->payment_time)
            );
        }
        $this->output($result);
    }
}

